package cn.itcast.oa.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;
import cn.itcast.oa.base.BaseDAOimpl;
import cn.itcast.oa.cfg.Configuration;
import cn.itcast.oa.model.Forum;
import cn.itcast.oa.model.PageBean;
import cn.itcast.oa.model.Reply;
import cn.itcast.oa.model.Topic;
import cn.itcast.oa.service.ReplyService;

@Service
@SuppressWarnings("unchecked")
public class ReplyServiceImpl extends BaseDAOimpl<Reply> implements ReplyService{

	@Override
	public List<Reply> findByTopic(Topic topic) {
		// TODO Auto-generated method stub
		return getSession().createQuery(//
				"FROM Reply r WHERE r.topic=? ORDER BY r.postTime ASC")//
				.setParameter(0, topic)
				.list();
	}
	
	@Override
	public void save(Reply reply){
	 getSession().save(reply);
	 Topic topic=reply.getTopic();
	 topic.setLastReply(reply);
	 topic.setLastUpdateTime(reply.getPostTime());
	 topic.setReplyCount(topic.getReplyCount()+1);
	 getSession().update(topic);
	 
	 Forum forum=topic.getForum();
	 forum.setArticleCount(forum.getArticleCount()+1);
	 getSession().update(forum);
	 
	}

	@Deprecated
	public PageBean getPageBean(int pageNum, Topic topic) {
		int pageSize=Configuration.getPageSize();
		
	    List recordList=getSession().createQuery(//
	    		"FROM Reply r WHERE r.topic=? ORDER BY r.postTime DESC")//
	    		.setParameter(0, topic)
	    		.setFirstResult((pageNum - 1) * pageSize)
	    		.setMaxResults(pageSize)
	    		.list();
		Long recordCount=(Long) getSession().createQuery(//
				"SELECT COUNT(*) FROM Reply r WHERE r.topic=?")//
				.setParameter(0, topic)
				.uniqueResult();
		return new PageBean(pageNum,pageSize,recordList,recordCount.intValue());
	}
	
}
